package com.ming.sportdemo.filter;

import com.ming.sportdemo.Exception.RoleException;
import com.ming.sportdemo.annotation.NeedFinalRole;
import com.ming.sportdemo.annotation.NeedRole;
import com.ming.sportdemo.service.UtilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.Objects;

public class UtilAuthentication implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("管理员拦截器启动...");
        if (!(handler instanceof HandlerMethod)){
            System.out.println("nothander");
            return true;
        }
        String role = URLDecoder.decode(request.getHeader("role"),"UTF-8");//从前端请求头获取role
        System.out.println("role:"+role);
        HandlerMethod handlerMethod=(HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(NeedRole.class)){
            if (role.equals("管理员")||role.equals("超级管理员")){
                System.out.println("身份验证成功，可以继续操作！");
                return true;
            }else {
                throw new RoleException("身份验证失败，角色权限异常!");
            }
        }
        if (method.isAnnotationPresent(NeedFinalRole.class)){
            if (role.equals("超级管理员")){
                System.out.println("身份验证成功，可以继续操作！");
                return true;
            }else{
                throw new RoleException("身份验证失败，角色权限异常！");
            }
        }
        return true;
    }
}
